//
//  IdeaCalendarViewController.m
//  planner
//
//  Created by 함동균 on 2014. 3. 22..
//  Copyright (c) 2014년 idea. All rights reserved.
//

#import "IdeaCalendarVC.h"

@interface IdeaCalendarViewController ()
@property (weak, nonatomic) IBOutlet UINavigationItem *navigationTitle;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *yearViewButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addTaskButton;
@property (strong, nonatomic) UIBarButtonItem *searchButton;
@property (weak, nonatomic) IBOutlet UIScrollView *calendarMonthScrollView;
@end

@implementation IdeaCalendarViewController

#pragma mark Property setter and getter
@synthesize year = _year;
@synthesize month = _month;

- (NSInteger)year
{
    if (!_year) {
        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        NSDateComponents *dateComponents = [gregorianCalendar components:units
                                                                fromDate:[NSDate date]];
        _year = dateComponents.year;
    }
    return _year;
}

- (void)setYear:(NSInteger)year
{
    _year = year;
}

- (NSInteger)month
{
    if (!_month) {
        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        NSDateComponents *dateComponents = [gregorianCalendar components:units
                                                                fromDate:[NSDate date]];
        _month = dateComponents.month;
    }
    return _month;
}

- (void)setMonth:(NSInteger)month
{
    _month = month;
}

#pragma initializer
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark View controller lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.tabBarName = TAB_BAR_CALENDAR;
    
    // Add Search Button
    self.searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                                                      target:self
                                                                      action:@selector(searchTask:)];
    NSMutableArray *rightBarItems = [[NSMutableArray alloc]init];
    [rightBarItems addObjectsFromArray:self.navigationItem.rightBarButtonItems];
    [rightBarItems addObject: self.searchButton];
    self.navigationItem.rightBarButtonItems = rightBarItems;
    
    // Add Pages to the Scroll View
    [self.calendarMonthScrollView setContentSize:CGSizeMake(3 * self.calendarMonthScrollView.bounds.size.width , self.calendarMonthScrollView.bounds.size.height)];
    [self.calendarMonthScrollView setPagingEnabled:YES];
    [self redrawMonthGrid];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        [self setViewConstraint:self.calendarMonthScrollView forWidth:self.view.frame.size.width / 2.0];
        [self.tabBarController.tabBar setTranslucent:YES];
        [self.tabBarController.tabBar setHidden:YES];
    } else {
        [self setViewConstraint:self.calendarMonthScrollView forWidth:self.view.frame.size.width];
        [self.tabBarController.tabBar setTranslucent:NO];
        [self.tabBarController.tabBar setHidden:NO];
    }
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) { // iOS 7
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    } else { // iOS 6
        if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        } else {
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        }
    }
    
    [self redrawMonthGrid];
}

- (BOOL)hidesBottomBarWhenPushed
{
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)prefersStatusBarHidden
{
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return YES;
    } else {
        return NO;
    }
}

- (void)setViewConstraint:(UIScrollView*)view forWidth:(CGFloat)width
{
    for (NSLayoutConstraint *constraint in view.constraints) {
        if (constraint.firstAttribute == NSLayoutAttributeWidth) {
            constraint.constant = width;
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Scroll View Delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int page = self.calendarMonthScrollView.contentOffset.x / self.calendarMonthScrollView.frame.size.width;
    
    if (page < 1) {
        if (self.month > 1) {
            self.month = self.month - 1;
        } else {
            self.year = self.year - 1;
            self.month = 12;
        }
        [self redrawMonthGrid];
    } else if (page > 1) {
        if (self.month < 12) {
            self.month = self.month + 1;
        } else {
            self.year = self.year + 1;
            self.month = 1;
        }
        [self redrawMonthGrid];
    }
}

#pragma mark Data update
- (void)redrawMonthGrid
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    self.navigationTitle.title = [[df monthSymbols] objectAtIndex:self.month - 1];
    self.yearViewButton.title = [NSString stringWithFormat:@"%d", self.year];
    [self drawScrollView];
    [self updateTheme];
}

- (void)drawScrollView
{
    if (self.month) {
        // Remove all views
        for (UIView *subview in self.calendarMonthScrollView.subviews) {
            [subview removeFromSuperview];
        }
        
        [self.calendarMonthScrollView setContentOffset:CGPointMake(self.calendarMonthScrollView.bounds.size.width, 0)];
        CGRect frame = self.calendarMonthScrollView.bounds;
        
        // Add previous month view
        IdeaCalendarMonthView *previousMonthView = [[IdeaCalendarMonthView alloc] initWithFrame:CGRectOffset(frame, -frame.size.width, 0)];
        if (self.month > 1) {
            previousMonthView.month = [CalendarMonth setYear:self.year
                                                       month:self.month - 1
                                      inManagedObjectContext:[self getManagedObjectContext]];
        } else {
            previousMonthView.month = [CalendarMonth setYear:self.year - 1
                                                       month:12
                                      inManagedObjectContext:[self getManagedObjectContext]];
        }
        [self.calendarMonthScrollView addSubview:previousMonthView];
        self.calendarMonthScrollView.delegate = self;
        
        // Add current month view
        IdeaCalendarMonthView *currentMonthView = [[IdeaCalendarMonthView alloc] initWithFrame:frame];
        currentMonthView.month = [CalendarMonth setYear:self.year
                                                  month:self.month
                                 inManagedObjectContext:[self getManagedObjectContext]];
        [self.calendarMonthScrollView addSubview:currentMonthView];
        
        // Add next month view
        IdeaCalendarMonthView *nextMonthView = [[IdeaCalendarMonthView alloc] initWithFrame:CGRectOffset(frame, frame.size.width, 0)];
        if (self.month < 12) {
            nextMonthView.month = [CalendarMonth setYear:self.year
                                                   month:self.month + 1
                                  inManagedObjectContext:[self getManagedObjectContext]];
        } else {
            nextMonthView.month = [CalendarMonth setYear:self.year + 1
                                                   month:1
                                  inManagedObjectContext:[self getManagedObjectContext]];
        }
        [self.calendarMonthScrollView addSubview:nextMonthView];
    }
}

#pragma mark Theme update
- (void)updateTheme
{
    [super updateTheme];
    
    for (IdeaCalendarMonthView *monthView in self.calendarMonthScrollView.subviews) {
        [monthView updateTheme];
    }
}

#pragma mark Actions
- (IBAction)searchTask:(id)sender {

}
@end
